package com.bridgeintelligent.tag.webserver.dim.mgmt.service.item;

import com.bridgeintelligent.tag.mapper.DimItemMapper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.BaseCode;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimItem;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimRep;
import com.wayneleo.quickstart.framework.IDGenerator;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by JackCheung on 2019/9/10 3:53 AM.
 */
@Service
public class DimItemService implements IDimItemService {

    private DimItemMapper dimItemMapper;

    public DimItemService(DimItemMapper dimItemMapper) {
        this.dimItemMapper = dimItemMapper;
    }

    @Override
    public DimRep list(String dimId) {
        return new DimRep<>(dimItemMapper.findSortedList(dimId), BaseCode.SUCCESS);
    }

    @Override
    public DimRep del(String id) {
        dimItemMapper.del(id);
        return new DimRep<>(0);
    }

    @Override
    public DimRep add(String dimId, String itemNo, String itemName) {
        int result = dimItemMapper.findOne(dimId, itemNo);
        if (result != 0) {
            return new DimRep<>("新增失败，标签项代码重复！", BaseCode.FAIL);
        }
        dimItemMapper.add(IDGenerator.gen(), dimId, itemNo, itemName, format(new Date()));
        return new DimRep<>(0);
    }

    @Override
    public DimRep update(String id, String dimId, String itemNo, String definition) {
        DimItem dimItem = new DimItem();
        dimItem.setId(id);
        dimItem.setDimId(dimId);
        dimItem.setItemNo(itemNo);
        dimItem.setItemName(definition);
        dimItem.setUpdateDate(format(new Date()));
        dimItemMapper.update(dimItem);
        return new DimRep<>(0);
    }

    private static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }
}
